package com.sqfw.project.zj.service.impl;

import com.sqfw.common.utils.SecurityUtils;
import com.sqfw.common.utils.StringUtils;
import com.sqfw.project.knowledge.service.KlContentService;
import com.sqfw.project.system.domain.SysDept;
import com.sqfw.project.system.domain.SysDictData;
import com.sqfw.project.system.domain.SysUser;
import com.sqfw.project.system.mapper.SysDeptMapper;
import com.sqfw.project.wp.domain.WpInfo;
import com.sqfw.project.wp.domain.WpInfoCall;
import com.sqfw.project.wp.mapper.WpInfoCallMapper;
import com.sqfw.project.wp.mapper.WpInfoMapper;
import com.sqfw.project.wp.service.IWpInfoService;
import com.sqfw.project.zj.domain.ZjRecord;
import com.sqfw.project.zj.domain.ZjRecordScore;
import com.sqfw.project.zj.domain.ZjSoundCase;
import com.sqfw.project.zj.mapper.ZjRecordMapper;
import com.sqfw.project.zj.service.IZjRecordScoreService;
import com.sqfw.project.zj.service.IZjRecordService;
import com.sqfw.project.zj.service.IZjSoundCaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 录音信息Service业务层处理
 *
 * @author lx
 * @date 2023-07-05
 */
@Service
@Slf4j
public class ZjRecordServiceImpl implements IZjRecordService {
    @Autowired
    private ZjRecordMapper zjRecordMapper;

    @Autowired
    private IZjRecordScoreService iZjRecordScoreService;

    @Autowired
    private IZjSoundCaseService iZjSoundCaseService;

    @Autowired
    private IWpInfoService iWpInfoService;

    @Autowired
    private WpInfoMapper wpInfoMapper;
    @Autowired
    private WpInfoCallMapper wpInfoCallMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private KlContentService klContentService;

    private static final Long zxDeptId = 103L;

    private static final Long hfDeptId = 107L;


    /**
     * 查询录音信息
     *
     * @param recordId 录音信息主键
     * @return 录音信息
     */
    @Override
    public ZjRecord selectZjRecordByRecordId(String recordId) {
        ZjRecord zjRecord = zjRecordMapper.selectZjRecordByRecordId(recordId);
        WpInfoCall wpInfoCall = new WpInfoCall();
        wpInfoCall.setRecordUuid(recordId);
        List<WpInfoCall> wpInfoCalls = wpInfoCallMapper.selectWpInfoCallList(wpInfoCall);
        WpInfoCall call = wpInfoCalls.stream().findAny().orElse(null);
        if (call != null) {
            zjRecord.setWpid(call.getWpid());
        }
        List<ZjRecordScore> zjRecordScores = new ArrayList<>();
        SysDictData dictData = new SysDictData();
        dictData.setDictType("zj_score_items");
        // 配置文件中查询，评分配置
        List<SysDictData> sysDictDataList = klContentService.getKnowledgeShapeList(dictData);
        // 默认每4条数据做为一组
        int count = sysDictDataList.size() / 4;
        for (int i = 0; i < count; i++) {
            String str = "zj_score_items" + "_" + i;
            ZjRecordScore zjRecordScore = new ZjRecordScore();
            for (int j = 0; j < 4; j++) {
                String str2 = str + "_" + j;
                for (SysDictData sysDictData : sysDictDataList) {
                    if (str2.equals(sysDictData.getDictLabel())) {
                        if (j == 0) {
                            String[] strings = sysDictData.getDictValue().split("--");
                            zjRecordScore.setItemId(strings[0]);
                            zjRecordScore.setItemClass1(strings[1]);
                            // scoreStandard
                            zjRecordScore.setScoreStandard(sysDictData.getRemark());
                            break;
                        } else if (j == 1) {
                            // remark
                            zjRecordScore.setRemark(sysDictData.getRemark());
                            break;
                        } else if (j == 2) {
                            // score
                            zjRecordScore.setScore(sysDictData.getRemark());
                            break;
                        } else if (j == 3) {
                            // scoreSelects
                            zjRecordScore.setScoreSelects(sysDictData.getRemark());
                            break;
                        }
                    }
                }
            }
            zjRecordScores.add(zjRecordScore);
        }
        // 查询是否已经质检了
        ZjRecordScore zjRecordScore = new ZjRecordScore();
        zjRecordScore.setRecordId(recordId);
        List<ZjRecordScore> zjRecordScoreList = iZjRecordScoreService.selectZjRecordScoreList(zjRecordScore);
        // 已经质检过了,把之前的评分获取到
        if (!CollectionUtils.isEmpty(zjRecordScoreList)) {
            for (ZjRecordScore recordScore : zjRecordScores) {
                for (ZjRecordScore laoRecordScore : zjRecordScoreList) {
                    if (recordScore.getItemId().equals(laoRecordScore.getItemId())) {
                        recordScore.setScid(laoRecordScore.getScid());
                        recordScore.setScore(laoRecordScore.getScore());
                        break;
                    }
                }
            }
        }
        zjRecord.setZjRecordScores(zjRecordScores);
        return zjRecord;
    }

    /**
     * 查询最近的一条录音信息
     *
     * @return 录音信息
     */
    @Override
    public ZjRecord selectLastRecord() {
        return zjRecordMapper.selectLastRecord();
    }

    /**
     * 查询录音信息列表
     *
     * @param zjRecord 录音信息
     * @return 录音信息
     */
    @Override
    public List<ZjRecord> selectZjRecordList(ZjRecord zjRecord) {

        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long deptId = user.getDeptId();


        // 录音时长时间范围查询条件处理
        String recordTimeSelect = zjRecord.getRecordTimeSelect();
        if (StringUtils.isNotEmpty(recordTimeSelect)) {
            String[] strings = recordTimeSelect.split(",");
            zjRecord.setRecordTimeSelectStart(String.valueOf(Integer.valueOf(strings[0]) * 60 + Integer.valueOf(strings[1])));
            zjRecord.setRecordTimeSelectEnd(String.valueOf(Integer.valueOf(strings[2]) * 60 + Integer.valueOf(strings[3])));
        }
        // 内容类别查询
        List<List<String>> classAllFind = zjRecord.getClassAllFind();
        //内容类别查询
        if (classAllFind == null || classAllFind.size() == 0) {
            zjRecord.setClassAll(null);
        } else {
            List<String> classAllCon = new ArrayList<>();
            for (List<String> strings : classAllFind) {
                classAllCon.add(strings.get(strings.size() - 1));
            }
            zjRecord.setClassAll(classAllCon);
        }
        List<ZjRecord> zjRecords = zjRecordMapper.selectZjRecordList(zjRecord);
        // 通话时长 秒 转换为 x分x秒
        for (ZjRecord zjRecord1 : zjRecords) {
            zjRecord1.setRecordSeconds(getSpecifyFormatRecord(zjRecord1.getRecordSeconds()));
            String department = zjRecord1.getDepartment();
            if (StringUtils.isNotEmpty(department)) {
                SysDept sysDept = sysDeptMapper.selectDeptById(Long.valueOf(department));
                zjRecord1.setDepartment(sysDept.getDeptName());

            }
            if (StringUtils.isNotEmpty(zjRecord1.getWpid())) {
                WpInfo info = wpInfoMapper.selectWpInfoByWpId(zjRecord1.getWpid());
                if (info != null) {
                    zjRecord1.setIsSoundCase(info.getIsSoundCases());
                }
            }
            //质检按钮状态
            zjRecord1.setZjButtonStatus(true);
            //录音按钮状态
            zjRecord1.setSoundButtonStatus(true);

            if (zxDeptId.equals(deptId) || hfDeptId.equals(deptId)) {
                zjRecord1.setZjButtonStatus(false);
                if (!(StringUtils.isNotEmpty(zjRecord1.getAgentId()) && user.getCode().equals(zjRecord1.getAgentId()))) {
                    zjRecord1.setSoundButtonStatus(false);
                }

            }


        }
        return zjRecords;
    }


    /**
     * 通话时长秒转化为 x分x秒
     *
     * @param recordSeconds 通话时长
     * @return
     */
    private String getSpecifyFormatRecord(String recordSeconds) {
        if (StringUtils.isEmpty(recordSeconds)) return "";
        int seconds = Integer.valueOf(recordSeconds);
        return seconds / 60 + "分" + seconds % 60 + "秒";
    }

    /**
     * 新增录音信息
     *
     * @param zjRecord 录音信息
     * @return 结果
     */
    @Override
    public int insertZjRecord(ZjRecord zjRecord) {
        if (zjRecord.getCreateTime() == null) {
            zjRecord.setCreateTime(new Date());
        }
        return zjRecordMapper.insertZjRecord(zjRecord);
    }

    /**
     * 修改录音信息
     *
     * @param zjRecord 录音信息
     * @return 结果
     */
    @Override
    public int updateZjRecord(ZjRecord zjRecord) {
        // 计算、保存分数
        List<ZjRecordScore> zjRecordScores = zjRecord.getZjRecordScores();
        int score = 0; // 总分

        for (ZjRecordScore zjRecordScore : zjRecordScores) {
            if (StringUtils.isNotEmpty(zjRecordScore.getScore())) {
                score += Integer.valueOf(zjRecordScore.getScore());
            }
            if (zjRecordScore.getScid() == null) {
                zjRecordScore.setItemDesc(zjRecordScore.getItemClass1());
                zjRecordScore.setScore(zjRecordScore.getScore());
                zjRecordScore.setRecordId(zjRecord.getRecordId());
                // 之前没有质检过（没有评分）
                iZjRecordScoreService.insertZjRecordScore(zjRecordScore);
            } else {
                // 之前评分过，更新各项历史得分
                iZjRecordScoreService.updateZjRecordScore(zjRecordScore);
            }
        }
        if (score <= 0) {
            zjRecord.setScore("0");
        } else {
            zjRecord.setScore(String.valueOf(score));
        }
        if (StringUtils.isNotEmpty(zjRecord.getWpid())) {
            if ("否".equals(zjRecord.getIsSoundCase())) {
                // 声音案例表中的记录删掉，工单表里的记录是否声音案例改为 否
                iZjSoundCaseService.delZjSoundCaseByWpid(zjRecord.getWpid());
                iWpInfoService.updateWpInfo2(zjRecord.getWpid());
            } else if ("是".equals(zjRecord.getIsSoundCase())) {
                //质检选择是声音案例
                WpInfo wpInfo = wpInfoMapper.selectWpInfoByWpId(zjRecord.getWpid());
                wpInfo.setIsSoundCases("是");
                wpInfo.setSubmitReason(zjRecord.getSubmitReason());
                wpInfoMapper.updateWpInfo(wpInfo);
                addSoundCase(wpInfo);
            }
        }
        zjRecord.setZjStatus("已质检");
        zjRecord.setZjType("已质检");
        SysUser user = SecurityUtils.getLoginUser().getUser();
        String nickName = user.getNickName();

        //质检员姓名
        zjRecord.setQcName(nickName);
        zjRecord.setQcNum(user.getCode());
        zjRecord.setUpdateTime(new Date());
        return zjRecordMapper.updateZjRecord(zjRecord);
    }

    /**
     * 增加声音案例
     */
    private void addSoundCase(WpInfo wpInfo) {
        // 添加声音案例
        ZjSoundCase zjSoundCase = new ZjSoundCase();
        zjSoundCase.setWpid(wpInfo.getWpid());
        zjSoundCase.setAcceptStatus("待采纳");
        zjSoundCase.setIsSoundCases("是");
        String code = SecurityUtils.getLoginUser().getUser().getCode();
        zjSoundCase.setCreateBy(code);
        zjSoundCase.setCreateTime(new Date());
        zjSoundCase.setSender(wpInfo.getSender());
        zjSoundCase.setSubmitReason(wpInfo.getSubmitReason());
        iZjSoundCaseService.addZjSoundCase(zjSoundCase);
    }

    /**
     * 批量删除录音信息
     *
     * @param recordIds 需要删除的录音信息主键
     * @return 结果
     */
    @Override
    public int deleteZjRecordByRecordIds(String[] recordIds) {
        return zjRecordMapper.deleteZjRecordByRecordIds(recordIds);
    }

    /**
     * 删除录音信息信息
     *
     * @param recordId 录音信息主键
     * @return 结果
     */
    @Override
    public int deleteZjRecordByRecordId(String recordId) {
        return zjRecordMapper.deleteZjRecordByRecordId(recordId);
    }

    /**
     * 获取关联工单号
     *
     * @param recordUuid 录音ID
     * @return 工单号
     */
    @Override
    public String getWpidByRecordId(String recordUuid) {
        return zjRecordMapper.getWpidByRecordId(recordUuid);
    }
}
